package nancal.mp.db.mongo.entity.shop

import nancal.mp.db.mongo.*
import nancal.mp.db.mongo.base.shop.*
import nancal.mp.db.mongo.base.wx.OpenIdName
import nancal.mp.db.mongo.entity.CorpCategory
import nancal.mp.db.mongo.entity.Corporation
import nancal.mp.db.mongo.entity.sys.BrandInfo
import nancal.mp.db.mongo.entity.sys.CategoryInfo
import nbcp.base.db.*
import nbcp.base.db.annotation.DbEntityGroup
import nbcp.base.db.annotation.DbEntityIndex
import nbcp.base.db.annotation.DbEntityIndexes
import nbcp.base.model.BaseMarkEntity
import nbcp.myoql.db.comm.DbEntityCascadeDefine
import nbcp.myoql.db.comm.RemoveToSysDustbin
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDateTime

/**
 * Created by yuxh on 2018/11/5
 */

/**
 * 活动
 */
@Document
@DbEntityGroup("shop")
open class ShopActivityInfo(
    var type: ShopActivityTypeEnum? = null,
    var detail: String = "",
    var banner: IdUrl = IdUrl(), //淘对Banner
    var code: String = "",
    var rule: ShopActivityRuleData = ShopActivityRuleData(),
    var order: Float = 0.0F     //排序
) : BaseMarkEntity()


/**
 * 券
 */
@Document
@DbEntityGroup("shop")
open class ShopCouponInfo(
        var type: CouponTypeEnum = CouponTypeEnum.Discount,
        var until: Int = 0,                 //满
        var discountRate: Int = 0,          // 打折
        var discountReduce: Int = 0,        // 优惠金额
        var count: Int = 0,                 //发行张数
        var transformUser: Boolean = false,      //可转赠
        var rule: ShopActivityRuleData = ShopActivityRuleData(),
        var corp: IdName = IdName()
) : BaseMarkEntity()


/**
 * 用户领券
 */
@Document
@DbEntityGroup("shop")
class UserCouponInfo(
        var code: String = "",
        var index: Int = 0,      //发行的索引
        var user: IdName = IdName()
) : ShopCouponInfo()


@Document
@DbEntityGroup("shop")
@RemoveToSysDustbin
//@DbEntityCascades(
//    DbEntityCascadeDefine("brandPath",  BrandInfo::class),
//    DbEntityCascadeDefine("corpCategoryPath",  nancal.mp.db.mongo.entity.CorpCategory::class),
//    DbEntityCascadeDefine("categoryPath",  CategoryInfo::class),
//    DbEntityCascadeDefine("corp", nancal.mp.db.mongo.entity.Corporation::class)
//)

@DbEntityCascadeDefine("brandPath.id", "brandPath.name", BrandInfo::class )
@DbEntityCascadeDefine("corpCategoryPath.id", "corpCategoryPath.name", CorpCategory::class )
@DbEntityCascadeDefine("categoryPath.id", "categoryPath.name", CategoryInfo::class )
@DbEntityCascadeDefine("corp.id", "corp.name", Corporation::class )
data class ProductInfo(
        var name: String = "",
        var slogan: String = "", //口号。少于16个字
        var brandPath: MutableList<IdName> = mutableListOf(),   //引用平台品牌
        var corpCategoryPath: MutableList<IdName> = mutableListOf(), //引用自定义分类
        var categoryPath: MutableList<IdName> = mutableListOf(), //平台分类路径

        var barCode: String = "", //条形码
        var parameters: MutableList<ProductParameterData> = mutableListOf(),
        var showImages: MutableList<IdUrl> = mutableListOf(),  //轮播图片

        var images: MutableList<IdUrl> = mutableListOf(), //产品详情图片
        var status: ProductStatusEnum = ProductStatusEnum.Online,

        var video: IdUrl = IdUrl(),

        var detail: String = "", //商品详情前面的文字 .
        var remark: String = "", //商品详情最后的文字 .

        var corp: IdName = IdName(),

        var isGroupProduct: Boolean = false,                        //是否是组合商品
        var subProducts: MutableList<IdName> = mutableListOf(),     //如果是组合商品

        var logisticsFee: LogisticsFeeSet = LogisticsFeeSet(),      //物流费用

        //sku
        var skuDefines: MutableList<SkuDefineData> = mutableListOf(),
        var skuStockPrice: MutableList<ProductSkuStockPrice> = mutableListOf()

) : BaseMarkEntity() {
    val logo: IdUrl
        get() = this.showImages.firstOrNull() ?: IdUrl()

    //最低价格(含活动)
    val minPrice: Int
        get() {
            return this.skuStockPrice.filter { it.stock > 0 }.map { it.salePrice }.minOrNull() ?: 0
        }

    //最高价格(含活动)
    val maxPrice: Int
        get() {
            return this.skuStockPrice.filter { it.stock > 0 }.map { it.salePrice }.maxOrNull() ?: 0
        }

    //所有Sku的总库存量.
    val stock: Int
        get() {
            return this.skuStockPrice.map { it.stock }.sum();
        }
}

/**
 * 按商家拆分的子订单
 */
class CorpOrderInfo(
        var index: Int = 0,                 //从1开始的序号
        var status: CorpOrderStatusEnum = CorpOrderStatusEnum.Created,
        var corp: IdName = IdName(),
        var amount_discount: Int = 0,       //商家优惠金额
        //发货信息
        var deliveryInfo: OrderDeliveryData = OrderDeliveryData(),

        var details: MutableList<OrderInfo_ProductItem> = mutableListOf(), //商品
        var refunds: MutableList<RefundData> = mutableListOf(),             //退款信息

        var coupons: MutableList<UserCouponInfo> = mutableListOf(),         //用户使用的适用于该商家订单的优惠券
        var evaluates: MutableList<EvaluateData> = mutableListOf(),         //评价
        var commissionLogs: MutableList<CommissionData> = mutableListOf()   //是否已经分成 返现状态
) {
    //总金额. 稳定值。 = 商品实售金额 + 运费
    val amount: Int
        get() = this.details.map { it.amount }.sum()


    val freight: Int            //总运费
        get() = this.details.map { it.freight }.sum()

    /**
     * 应付金额 = 总金额 - 优惠券金额 - 商家优惠金额
     */
    val payableAmount: Int = amount + freight - amount_discount;
}


/**
 * 用户下单的主订单
 */
@Document
@DbEntityGroup("shop")
@DbEntityIndexes(DbEntityIndex("orderCode", unique = true))
open class OrderInfo(
    var orderCode: String = "", //订单号
    var status: OrderStatusEnum = OrderStatusEnum.Created,
    var createBy: OpenIdName = OpenIdName(),

    var subOrders: MutableList<CorpOrderInfo> = mutableListOf(),     //子订单
    var receiveAddress: ReceiveAddressDataInfo = ReceiveAddressDataInfo(),

    var payInfo: OrderPayInfo = OrderPayInfo(),
    var coupons: MutableList<UserCouponInfo> = mutableListOf(),         //用户使用的适用于整体订单的优惠券
    var remark: String = ""    //消费者填写说明。

) : BaseMarkEntity() {

    //总金额. 稳定值。 = 商品实售金额 + 运费
    val amount: Int
        get() = this.subOrders.map { it.amount }.sum()


    val freight: Int            //总运费
        get() = this.subOrders.map { it.freight }.sum()

    /**
     * 应付金额 = 总金额 - 优惠券金额 - 商家优惠金额
     */
    val payableAmount: Int
        get() = this.subOrders.map { it.payableAmount }.sum()

    //是否可以发货.
    val canDeliver: Boolean
        get() {
            //普通订单,已支付.
            return this.status == OrderStatusEnum.Payed;
        }

    companion object {
    }
}

/**
 * 定义皮肤，（不支持自定义布局）
 */
@Document
@DbEntityGroup("shop")
data class ThemeInfo(
        var name: String = "",
        var logo: IdUrl = IdUrl(),
        var images: MutableList<IdUrl> = mutableListOf(),
        var remark: String = "",
        var shopSiteVar: StyleDefineData = StyleDefineData()
) : BaseMarkEntity()


//合伙人定义
@Document
@DbEntityGroup("shop")
data class PartnerConfig(
        var banner: IdUrl = IdUrl(),   //banner
        var name: String = "",      //合伙人名称
        var type: UserPartnerTypeEnum? = null, //合伙人类型
        var remark: String = "",    //合伙人简介,介绍,规则介绍
        var commission: Int = 0     //分成比例,每万元提成
) : BaseMarkEntity()

/**
 * 活动商品，不抽成的商品分类
 */
@Document
@DbEntityGroup("shop")
data class ExecuteCommissionCategory(
        var categoryPath: MutableList<IdCodeName>,
        var remark: String = "",
        var createBy: IdName = IdName(),
        var startAt: LocalDateTime? = null,
        var endAt: LocalDateTime? = null
) : BaseMarkEntity()

/**
 * 活动商品，不抽成的商品
 */
@Document
@DbEntityGroup("shop")
data class ExecuteCommissionProduct(
        var product: IdNameUrl = IdNameUrl(),
        var corp: IdName = IdName(),
        var remark: String = "",
        var createBy: IdName = IdName(),
        var startAt: LocalDateTime? = null,
        var endAt: LocalDateTime? = null
) : BaseMarkEntity()

/**
 * 收藏商品
 */
@Document
@DbEntityGroup("shop")
data class ProductFavorite(
        var corp: IdName = IdName(),
        var product: ProductCardData = ProductCardData(),
        var user: IdName = IdName()
) : BaseMarkEntity()

/**
 * 收藏商家
 */
@Document
@DbEntityGroup("shop")
data class StoreFavorite(
        var corp: IdNameUrl = IdNameUrl(),
        var user: IdName = IdName()
) : BaseMarkEntity()

/**
 * 物流费用模板设置
 */
@Document
@DbEntityGroup("shop")
data class LogisticsFeeSet(
        var name: String = "",
        var type: LogisticsFeeTypeEnum = LogisticsFeeTypeEnum.None,

        var startNumber: Int = 0,   //起步数量
        var startPrice: Int = 0,    //起步价格
        var cities: MutableList<CodeName> = mutableListOf(), //城市 ， 0=全国
        var stepNumber: Int = 0,    //步长
        var stepPrice: Int = 0,     //步长费用

        var corp: IdName = IdName()
) : BaseMarkEntity()

/**
 * 购物车
 */
@Document
@DbEntityGroup("shop")
data class ShoppingCart(
        var product: IdName = IdName(), //绑定的商品
        var skuItemData: SkuItemData = SkuItemData(),
        var number: Int = 0, //数量
        var price: Int = 0, //单价
        var order: Float = 0F,   //排序
        var checked: Boolean = false, //是否选中
        var createBy: IdName = IdName(),
        var corp: IdName = IdName()
) : BaseMarkEntity()


/**
 * 每月统计数据 , 期末余额统计
 */
@Document
@DbEntityGroup("shop")
data class MonthStaticsData(
        var year: Int = 0,
        var month: Int = 0,
        var score: Int = 0
) : BaseMarkEntity()

